import type { TableData, TableInstance,TableRowSelection } from '@arco-design/web-vue';
import { Message, Modal } from '@arco-design/web-vue';
import {reactive, ref} from 'vue';
import { Options as paginationOptions, usePagination } from './usePagination';
import {SUESSCODE} from "@/types/const";

interface Options<T, U> {
  formatResult?: (data: T[]) => U[];
  onSuccess?: () => void;
  immediate?: boolean;
  rowKey?: keyof T;
  paginationOption?: paginationOptions;
}

interface PaginationParams {
  page: number;
  limit: number;
}
type Api<T> = (
  params: PaginationParams
) => Promise<ApiRes<PageRes<T[]>>> | Promise<ApiRes<T[]>>;



/**
 * desc 表格操作
 */
export function useTable<T extends U, U = T>(
  api: Api<T>,
  options?: Options<T, U>
) {
  const { formatResult, onSuccess, immediate, rowKey } = options || {};
  const loading = ref(false);
  const tableData: Ref<U[]> = ref([]);
  const { pagination, setTotal } = usePagination(
    () => getTableData(),
    options?.paginationOption
  );
  async function getTableData() {
    try {
      loading.value = true;
      const res = await api({
        page: pagination.current,
        limit: pagination.pageSize,
      });
      const data = !Array.isArray(res.data) ? res.data.list : res.data;
      tableData.value = formatResult ? formatResult(data) : data;
      const total = !Array.isArray(res.data) ? res.data.total : data.length;
      setTotal(total);
      onSuccess && onSuccess();
    } finally {
      loading.value = false;
    }
  }

  // 是否立即触发
  const isImmediate = immediate ?? true;
  isImmediate && getTableData();

  // 多选
  const selectedKeys = ref<(string | number)[]>([]);
  const select: TableInstance['onSelect'] = (rowKeys) => {
    selectedKeys.value = rowKeys;
  };
  // 全选
  const selectAll: TableInstance['onSelectAll'] = (checked) => {
    const key = rowKey ?? 'id';
    const arr = (tableData.value as TableData[]).filter(
      (i) => !(i?.disabled ?? false)
    );
    selectedKeys.value = checked ? arr.map((i) => i[key as string]) : [];
  };

  // 创建行选择器
   const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: true,
  });

  // 查询
  const search = () => {
    selectedKeys.value = [];
    pagination.onChange(1);
  };

  // 刷新
  const refresh = () => {
    getTableData();
  };

  // 删除
  const handleDelete = async <T>(
    deleteApi: () => Promise<ApiRes<T>>,
    options?: {
      title?: string;
      content?: string;
      successTip?: string;
      showModal?: boolean;
    }
  ): Promise<boolean | undefined> => {
    const onDelete = async () => {
      try {
        const res = await deleteApi();
        if (res.code ===SUESSCODE) {
          Message.success(options?.successTip || '删除成功');
          selectedKeys.value = [];
          await getTableData();
        }
        return true;
      } catch (error) {
        return false;
      }
    };
    const flag = options?.showModal ?? true; // 是否显示对话框
    if (!flag) {
      return onDelete() ;
    }
    Modal.warning({
      title: options?.title || '提示',
      content: options?.content || '是否确定删除该条数据？',
      okButtonProps: { status: 'danger' },
      hideCancel: false,
      maskClosable: false,
      onBeforeOk: onDelete,
    });
  };

  return {
    loading,
    tableData,
    getTableData,
    search,
    pagination,
    selectedKeys,
    select,
    selectAll,
    handleDelete,
    refresh,
    rowSelection
  };
}
